<?php
// Include config file
include_once('./common.php');

// Connect to database
$link = dbConnect();
$output = "";

//see what action we need to do
if(isset($_POST['action'])){
	switch($_POST['action']){
		case "updateUser":
			updateUser();
		break;
		
		case "loadUser":
			loadUser();
		break;
		
		case "viewUser":
			viewUser();
		break;
	}
}

//output to flash
echo $output;

//if everything is ok, close the link to mysql
if(strchr($output, "okay")){
	mysql_close($link);
}

function updateUser(){
	global $output, $link;
	
	$abImgDir = $_POST['abImgDir'];
	
	//escape some common vars off the top
	$userID = mysql_real_escape_string($_POST['userID']);
	$email = mysql_real_escape_string($_POST['email']);
	
	// If email is invalid...
	if (!checkEmail($email)) {
		echo "output=emailFail";
		mysql_close($link);
		return;
	}
	
	//check the email to make sure it's not already used
	$result = mysql_query("SELECT email FROM ".TABLE_PREFIX."_users WHERE email = '".$email."' AND userID != ".$userID);
	if(mysql_num_rows($result) > 0){
		echo "output=emailInUse";
		mysql_close($link);
		return;
	}
	
	//we may need to update avatar and password so make a var to hold on to those possible extra SET queries
	$queryExtra = "";
	
	//check for an avatar
	if(isset($_POST['avatar'])){
		//get the user's current avatar
		$result = mysql_query("SELECT avatarURL FROM ".TABLE_PREFIX."_users WHERE userID = ".$userID);
		$data = mysql_fetch_object($result);
		$currentAvatar = stripslashes($data->avatarURL);
		
		//delete the old one first if it's on the file system
		if(substr($currentAvatar, 0, 4) != "http" && $currentAvatar != ""){
			//off the file system you go!
			@unlink($abImgDir.$currentAvatar);
		}
		$queryExtra .= ", avatarURL = '".mysql_real_escape_string($_POST['avatar'])."'";
	}
	
	//do a quick password check
	$password = "";
	if(isset($_POST['password'])){
		$password = mysql_real_escape_string($_POST['password']);
	}
	
	if(isset($_POST['changePassword'])){
		$password = mysql_real_escape_string($_POST['changePassword']);
	}
	
	if($password != ""){
		$queryExtra .= ", password = '".md5($password)."'";
	}

	$query = "UPDATE ".TABLE_PREFIX."_users SET  
	email = '".$email."',
	location = '".mysql_real_escape_string($_POST['location'])."',  
	signature = '".mysql_real_escape_string($_POST['signature'])."',
	homepage = '".mysql_real_escape_string($_POST['website'])."'".$queryExtra." WHERE userID = ".$userID;
	
	$result = mysql_query($query);
	
	if(!$result){
		echo "output=mysqlError&mysqlError=".mysql_error();
		mysql_close($link);
		return;
	}
	
	//update the social networking stuff
	foreach($_POST as $name => $value) {
		$chunks = explode($_POST['divider'], $name);
		if(count($chunks) > 1){
			//build the query
			if($value == ""){
				//delete from the dbase
				$query = "DELETE FROM ".TABLE_PREFIX."_users_networks WHERE userID = ".$userID." AND networkID = ".$chunks[0];
			}else{
				$query = "REPLACE INTO ".TABLE_PREFIX."_users_networks (userID, networkID, value) VALUES (".$userID.", ".$chunks[0].", '".mysql_real_escape_string($value)."')";
			}
			$result = mysql_query($query);
			if(!$result){
				echo "output=mysqlError&mysqlError=".mysql_error();
				mysql_close($link);
				return;
			}
		}
	}	
	
	$output .= "output=okay";
	if($password != ""){
		$output .= "&passwordChange=".md5($password);
	}
	
}

function loadUser(){
	global $output, $link;
	
	//if not updating, must be just a load
	$avatarDir = $_POST['avatarDir'];
	$userID = mysql_real_escape_string($_POST['userID']);
	
	$result = mysql_query("SELECT u.* FROM ".TABLE_PREFIX."_users u WHERE u.userID = ".$userID);
	
	if(!$result){
		echo "output=mysqlError&mysqlError=".mysql_error();
		mysql_close($link);
		return;
	}
	$data = mysql_fetch_object($result);
	
	$output .= "output=okay";		
	$output .= "&username=".stripslashes($data->username);
	$output .= "&email=".stripslashes($data->email);
	$output .= "&location=".stripslashes($data->location);
	$output .= "&signature=".stripslashes($data->signature);
	$output .= "&avatarURL=".stripslashes($data->avatarURL);
	$output .= "&canEditAvatar=".$data->canEditAvatar;
	$output .= "&website=".stripslashes($data->homepage);
	
	//this will load any social network fields we may have
	$networks = mysql_query("SELECT networkID, languageKey FROM ".TABLE_PREFIX."_social_networks WHERE isEnabled = 1");
	
	if(!$networks){
		echo "output=mysqlError&mysqlError=".mysql_error();
		mysql_close($link);
		return;
	}
	
	$totalNetworks = mysql_num_rows($networks);
	$output .= "&totalNetworks=".$totalNetworks;
	
	for($i = 0; $i < $totalNetworks; $i++){
		$socialData = mysql_fetch_object($networks);
		$output .= "&networkID".$i."=".$socialData->networkID;
		$output .= "&networkLanguage".$i."=".stripslashes($socialData->languageKey);
		$output .= "&networkValue".$i."=".checkNetwork($socialData->networkID, $userID);
	}
}

function checkNetwork($networkID, $userID){
	//this will return the value for the network ID that's passed in
	global $link;
	
	$result = mysql_query("SELECT value FROM ".TABLE_PREFIX."_users_networks WHERE networkID = ".$networkID." AND userID = ".$userID);
	
	if(mysql_num_rows($result) > 0){
		$data = mysql_fetch_object($result);
		return stripslashes($data->value);
	}else{
		return "";
	}
}

function viewUser(){
	global $output, $link;
	
	//if not updating, must be just a load
	$userID = mysql_real_escape_string($_POST['userID']);
	
	$result = mysql_query("SELECT u.* FROM ".TABLE_PREFIX."_users u WHERE u.userID = ".$userID);	
	
	if(!$result){
		echo "output=mysqlError&mysqlError=".mysql_error();
		mysql_close($link);
		return;
	}
	
	//see if they've posted and get that data
	$threadQuery = "SELECT t.topic, t.threadID
				FROM ".TABLE_PREFIX."_threads t, ".TABLE_PREFIX."_posts p
				WHERE p.userID = ".$userID."
				AND t.threadID = p.threadID
				ORDER BY posted DESC
				LIMIT 1";
	
	$threadResult = mysql_query($threadQuery);
	
	if(!$threadResult){
		echo "output=mysqlError&mysqlError=".mysql_error();
		mysql_close($link);
		return;
	}
	
	//all good, now let's output
	$output .= "output=okay";
	
	$lastThreadTopic = "";
	$lastThreadID = "";
	if(mysql_num_rows($threadResult) > 0){
		$threadData = mysql_fetch_object($threadResult);
		$lastThreadTopic = stripslashes($threadData->topic);
		$lastThreadID = $threadData->threadID;
	}
	
	$data = mysql_fetch_object($result);
	
	
	$output .= "&username=".stripslashes($data->username);
	//$output .= "&email=".stripslashes($data->email); //might add this back in later for some sort of internal mail system, not sure.
	$output .= "&location=".stripslashes($data->location);
	$output .= "&title=".stripslashes($data->title);
	$output .= "&posts=".number_format($data->posts);
	$output .= "&joined=".strftime("%b %d, %Y ", $data->joined);
	$output .= "&lastOnline=".strftime("%b %d, %Y %I:%M %p", $data->lastOnline);
	$output .= "&lastThreadTopic=".$lastThreadTopic;
	$output .= "&lastThreadID=".$lastThreadID;
	$output .= "&signature=".urlencode(stripslashes($data->signature));
	$output .= "&avatarURL=".stripslashes($data->avatarURL);
	$output .= "&website=".stripslashes($data->homepage);
	
	//get the social network data
	$result = mysql_query("SELECT un.value, sn.baseURL, sn.iconFileName 
						   FROM ".TABLE_PREFIX."_users_networks un, ".TABLE_PREFIX."_social_networks sn 
						   WHERE un.userID = ".$userID." 
						   AND sn.isEnabled = 1 
						   AND un.networkID = sn.networkID");
	
	if(!$result){
		echo "output=mysqlError&mysqlError=".mysql_error();
		mysql_close($link);
		return;
	}
	
	$totalNetworks = mysql_num_rows($result);
	$output .= "&totalNetworks=".$totalNetworks;
	
	for($i = 0; $i < $totalNetworks; $i++){
		$socialData = mysql_fetch_object($result);
		$output .= "&networkIcon".$i."=".stripslashes($socialData->iconFileName);
		$output .= "&networkURL".$i."=".stripslashes($socialData->baseURL.$socialData->value);
	}
	
}
?>